/* eslint-disable */
import Print from './print'
import { cleanUp } from './functions'

export default {
  print: (params, printFrame) => {
    // 如果是base64的pdf数据
    if (params.base64) {
      const bytesArray = Uint8Array.from(atob(params.printData), c => c.charCodeAt(0))
      createBlobAndPrint(params, printFrame, bytesArray)
      return
    }

    // 格式PDF URL
    params.printData = /^(blob|http)/i.test(params.printData)
      ? params.printData
      : window.location.origin + (params.printData.charAt(0) !== '/' ? '/' + params.printData : params.printData)

    // 通过HTTP请求获取文件（预加载）
    let req = new window.XMLHttpRequest()
    req.responseType = 'arraybuffer'

    req.addEventListener('load', () => {
      if ([200, 201].indexOf(req.status) === -1) {
        cleanUp(params)
        params.onError(req.statusText)

        // 由于我们没有可用的PDF文档，我们将停止打印作业
        return
      }

      // 打印请求的文档
      createBlobAndPrint(params, printFrame, req.response)
    })

    req.open('GET', params.printData, true)
    req.send()
  }
}

function createBlobAndPrint (params, printFrame, data) {
  // 将响应或base64数据传递到blob并创建本地对象URL
  let localPdf = new window.Blob([data], { type: 'application/pdf' })
  localPdf = window.URL.createObjectURL(localPdf)

  // 使用PDF文档URL设置iframe-src
  printFrame.setAttribute('src', localPdf)

  Print.send(params, printFrame)
}
